package com.springframework.core.service.impl;

import com.springframework.core.annotation.MyComponent;
import com.springframework.core.context.BeanPostProcessor;
import com.springframework.core.context.InitializingBean;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 *
 * @author youzhengjie
 */
@MyComponent
public class MyBeanPostProcess implements BeanPostProcessor, InitializingBean {

    @Override
    public Object postProcessorBeforeInitialization(Object bean, String beanName) {
        System.out.println("postProcessorBeforeInitialization");
        return bean;
    }

    @Override
    public Object postProcessorAfterInitialization(Object bean, String beanName) {
        System.out.println("postProcessorAfterInitialization");

        //cglib实现AOP
        if(beanName.equals("userServiceImpl")){
            Enhancer enhancer=new Enhancer();
            enhancer.setSuperclass(UserServiceImpl.class);
            enhancer.setCallback((MethodInterceptor) (o, method, objects, methodProxy) -> {
                //指定切入的方法
                if(method.getName().equals("getBeanName")){
                    System.out.println("aop之前");
                    Object invoke = method.invoke(bean, objects); //执行被代理的方法
                    System.out.println("aop之后");
                    return invoke;
                }
                return method.invoke(bean,objects);
            });
            Object proxyObject = enhancer.create();
            return proxyObject; //返回代理对象
        }


        return bean;
    }

    @Override
    public void afterPropertiesSet() {
        System.out.println("初始化bean");
    }
}
